package xiaohong.data;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class CalculatorDemo {


    public static void main(String[] args) {
        // 逆波兰表达式
        // 50 * 50 + 90 - 100 + 60 / 30   =>  50 50 * 90 + 100 - 60 30 / +
        // 25 * 10 - 250 + 100 / 50 + 80 - 2 - 40 * 2
        // 25 10 * 250 - 100 50 / + 80 + 2 - 40 2 * -
        String expr = "50 50 * 90 + 100 - 60 30 / +";
        String expr1 = "25 10 * 250 - 100 50 / + 80 + 2 - 40 2 * -";
        String[] split = expr.split(" ");
        String[] split1 = expr1.split(" ");
        List<String> exprList = Arrays.stream(split1).toList();

        System.out.println(exprList);

        Stack<Integer> stack = new Stack<>();
        exprList.forEach(item -> {
            if (item.matches("\\d+")) {
                stack.push(Integer.parseInt(item));
            }else {
                int num;
                switch (item) {
                    case "*" -> {
                        Integer num2 = stack.pop();
                        Integer num1 = stack.pop();
                        num = num1 * num2;
                    }
                    case "+" -> {
                        Integer num2 = stack.pop();
                        Integer num1 = stack.pop();
                        num = num1 + num2;
                    }
                    case "-" -> {
                        Integer num2 = stack.pop();
                        Integer num1 = stack.pop();
                        num = num1 - num2;
                    }
                    case "/" -> {
                        Integer num2 = stack.pop();
                        Integer num1 = stack.pop();
                        num = num1 / num2;
                    }
                    default -> throw new ArithmeticException("符号不正确");
                }
                stack.push(num);
            }
        });
        System.out.println("表达式的结果=" +stack.pop());
    }





}
